package simple

import (
	"context"
	"flag"
	"fmt"
	"log"
	"os"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// 读取参数
var (
	endPint    = "oss-cn-shenzhen.aliyuncs.com"
	uploadFile = os.Getenv("-f")
	region     = "cn-shenzhen"
	bucketName = "mchannel"
	client     *oss.Client
)

func validate() error {
	if uploadFile == "" {
		return fmt.Errorf("上传文件不能为空")
	}
	return nil
}

func getStringPathValue(command string, desc string) (value string, ok bool) {
	flag.StringVar(&value, command, "", desc)
	flag.Parse()
	return value, true
}

func init() {
	uploadFile, _ = getStringPathValue("f", "上传文件名称")
	config := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewStaticCredentialsProvider("LTAI5tEadeH3rAupuqF2E9o5", "rjuLILgGmmkmRtgZxxBfX8eoKWPpHw")).
		WithRegion(region)

	client = oss.NewClient(config)
}

func loadParam() map[string]string {
	var valueMap = make(map[string]string)
	return valueMap
}

func main() {
	loadParam()
	fmt.Println(getUrl("go.mod"))
	if err := validate(); err != nil {
		fmt.Println(err)
		os.Exit(0)
		return
	}
	if err := upload(uploadFile); err != nil {
		os.Exit(-1)
		return
	}
}

func getUrl(objectName string) string {
	result, _ := client.Presign(context.TODO(), &oss.GetObjectRequest{
		Bucket: oss.Ptr(bucketName),
		Key:    oss.Ptr(objectName),
	})

	return result.URL
}

func upload(uploadFile string) error {
	file, err := os.Open(uploadFile)
	if err != nil {
		log.Fatalf("failed to open file %v", err)
	}
	defer file.Close()

	result, err := client.PutObject(context.TODO(), &oss.PutObjectRequest{
		Bucket: oss.Ptr(bucketName),
		Key:    oss.Ptr(uploadFile),
		Body:   file,
	})
	if err != nil {
		log.Fatalf("failed to put object %v", err)
		return err
	}
	fmt.Printf("Successfully uploaded %s ETag: %v\n", uploadFile, result.ETag)
	return nil
}
